#!/usr/bin/env python

import sys

if (len(sys.argv) <= 1):
	print ("error: mapfile missing")
	sys.exit(1)

table = list()

cstring = "/** @ingroup keyboard\n"
cstring += " * @file keymap.h\n"
cstring += " * @brief keycode to keysymbol mappings\n\n"
cstring += " * generated with mkkeymap.py written by cameris (camerisdump@gmail.com)\n"

with open(sys.argv[1],'r') as mapfile:
	for line in mapfile:
		line = line.strip()
		if ( "" == line ):
			continue
		if ( '#' in line[0] ):
			if ('#!' in line):
				i = line.find("#!")
				cstring += " * "
				cstring += line[i+2:].strip()
				cstring +="\n"
			continue
		line = line.split('\t')
		if (len(line) >= 2 ):
			table.append(line)

table.sort()

if (len(table) < 1) :
	print ("error: mapfile does not contain anything")
	sys.exit(1)

names=["keymap_default", "keymap_shift","keymap_altgr", 
	"keymap_shift_altgr", "keymap_ctrl", "keymap_shift_ctrl", "keymap_ctrl_altgr"]

lists = list()
for i in range(1,len(names)+1):
	curlist = list()
	for sc in range(len(table)):
		try:
			if (table[sc][i] != ""):
				curlist.append([table[sc][0],table[sc][i]])
		except IndexError:
			pass
	lists.append(curlist)

cstring += " *\n * @author cameris camerisdump@gmail.com\n"
cstring += " */\n\n"
cstring += "#ifndef _KEYMAP_H_\n"
cstring += "#define _KEYMAP_H_\n\n"
cstring += "/** @brief keycode to keysymbol */\n"
cstring += "struct keymap {\n"
cstring += "\tuint8_t keycode;\n"
cstring += "\tuint16_t symbol;\n"
cstring += "};\n\n"

for i in range(len(names)):
	cstring +="const __flash struct keymap {:s}[] = ".format(names[i])
	cstring +="{ /* {{{ */"

	place = 0
	nl_after=60
	for pair in lists[i]:
		if (place%nl_after == 0):
			fill = "\n\t"
		else:
			fill = " "
		if (place == nl_after):
			place = 0

		valstr = fill
		valstr += "{"
		valstr += pair[0]
		valstr += ", "
		valstr += pair[1]
		valstr += "},"

		cstring += valstr

		place += len(valstr)	
		if (place > nl_after):
			place = nl_after

	cstring += "\n{0,0}}; /* }}} */\n\n"
cstring += "#endif\n"
cstring += "/* vim"
cstring += ":set foldmethod=marker: */"

with open("keymap.h", 'w') as cfile:
	cfile.write(cstring)
